﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Nextensions.GUI;

using EnvDTE;
using EnvDTE80;

namespace ReSearcher
{
    [Guid(GUID)]
    public partial class ReSearchControl : UserControl
    {
        public const string GUID = "9fdb1c6b-fc4a-4864-a1d2-c64259d9e81a";
        private DTE2 _dte;
        private ReSearchLogic _searcher;

        public ReSearchControl()
        {
            InitializeComponent();

            cmbLocation.Items.Add(ReSearchLogic.LocationSelection);
            cmbLocation.Items.Add(ReSearchLogic.LocationThisDoc);
            cmbLocation.Items.Add(ReSearchLogic.LocationAllOpen);
            cmbLocation.Items.Add(ReSearchLogic.LocationSolution);
            cmbLocation.Items.Add(ReSearchLogic.LocationProject);

            InputPersistence.AutoLoadUserInput(this);
            cmbFind.Focus();
        }

        public DTE2 DTE
        {
            get
            {
                return _dte;
            }
            set
            {
                _dte = value;
                _searcher = new ReSearchLogic(_dte);
            }
        }

        private void bFind_Click(object sender, EventArgs e)
        {
            StartSearch();
        }

        private void StartSearch()
        {
            InputPersistence.AutoSaveUserInput(this);
            RegexOptions opt = RegexOptions.Singleline | RegexOptions.Multiline;
            
            if (chkUp.Checked)
                opt |= RegexOptions.RightToLeft;

            if (chkIgnoreCase.Checked)
                opt |= RegexOptions.IgnoreCase;

            Regex re = new Regex(cmbFind.Text, opt);

            _searcher.Search(re, cmbLocation.Text, true);
        }

        internal void Activate()
        {
            if (_searcher == null)
                return;

            if (_searcher.Selection != null && !_searcher.Selection.IsEmpty)
                cmbLocation.SelectedIndex = 0;
            else if (cmbLocation.SelectedIndex <= 0)
                cmbLocation.SelectedIndex = 1;

            cmbFind.Focus();
        }

        private void ReSearchControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine("KeyPress");
        }

        private void ReSearchControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartSearch();
        }
    }
}
